const Controller = require('pages/controllers/controllers.js').controller;

App({
    onLaunch: function (option) {

        console.log( 'onLaunch option',option)

        wx.setStorageSync('shareparentId', '')
    
        let systemInfo = wx.getSystemInfoSync()
        // px转换到rpx的比例
        let pxToRpxScale = 750 / systemInfo.windowWidth;
        // 状态栏的高度
        let ktxStatusHeight = systemInfo.statusBarHeight * pxToRpxScale


        // 导航栏的高度
        let navigationHeight = 44 * pxToRpxScale


        this.globalData.statusBarHeight = ktxStatusHeight
        this.globalData.navigationHeight = navigationHeight
        this.globalData.pxToRpxScale = pxToRpxScale

        this.globalData.topNavigationHeight = ktxStatusHeight + navigationHeight
        let that = this;
        wx.getSystemInfo({

            success: function (res) {
                console.log(res)
                // 获取手机
                that.globalData.navHeight = res.statusBarHeight + 46;
                let model = res.model;
                if (model.search('iPhone X') != -1 || model.search('iPhone 11') != -1) {
                    that.globalData.isIphoneX = true
                }
                wx.setStorageSync('modelmes', model)
            }
        })

        // 展示本地存储能力
        var logs = wx.getStorageSync('logs') || []
        logs.unshift(Date.now())
        //获取token
        let token = wx.getStorageSync('logintoken') || '';

        //优先判断token
        // this.GetLogin();

        let query=option.query||wx.getLaunchOptionsSync().query
     
        if(query.scene){
           let scene=decodeURIComponent(query.scene)
   
            let arr  = scene.split('&')
   
            let obj={}
   
           for(let item of arr){
             item=item.split('=')
              if(item[0]=='parentid'){

              that.globalData.shareparentId=item[1]

              }
           }
        }else if(query.parentid){
            that.globalData.shareparentId=query.parentid
        }else{
            console.log('没有参数分享',query)
        }
     

      
         let userInfos=wx.getStorageSync('userInfo')||{}
        that.globalData.shareparentId=that.globalData.shareparentId==userInfos.id?'':that.globalData.shareparentId
        if(this.globalData.shareparentId) {

            wx.setStorageSync('shareparentId', that.globalData.shareparentId)

            this.GetLogin();
           
        }else if(token) {
          
             //延时判断微信服务器Session状态
             setTimeout(() => {
                wx.checkSession({
                    success: () => {
                        //session_key 未过期，并且在本生命周期一直有效
                    },
                    fail: () => {
                        // session_key 已经失效，需要重新执行登录流程
                        this.GetLogin();
                    }
                });
            }, 1500);
        } 
        else {
            //无token，直接登录
            this.GetLogin();

        }
        // wx.getUpdateManager 在 1.9.90 才可用，请注意兼容
        const updateManager = wx.getUpdateManager()

        updateManager.onCheckForUpdate(function (res) {
            // 请求完新版本信息的回调
            if (res.hasUpdate) {
                wx.showModal({
                    title: '更新提示',
                    content: '新版本已经准备好，是否马上重启小程序？',
                    success: function (res) {
                        if (res.confirm) {
                            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                            updateManager.applyUpdate()
                        }
                    }
                });
            }
        });
        updateManager.onUpdateReady(function () {
            wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否马上重启小程序？',
                success: function (res) {
                    if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                    }
                }
            });
        })
        updateManager.onUpdateFailed(function () {
            wx.showModal({
                title: '已有新版本',
                content: '新版本已经上线了，请删除当前小程序，重新搜索打开',
            })
        });

        // 获取用户信息
        wx.getSetting({
            success: res => {
                console.log(res)
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success: res => {
                            // 可以将 res 发送给后台解码出 unionId
                            this.globalData.wxuserInfo = res.userInfo
                            wx.setStorageSync('wxuserInfo', res.userInfo)
                            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                            // 所以此处加入 callback 以防止这种情况
                            if (this.userInfoReadyCallback) {
                                this.userInfoReadyCallback(res)
                            }

                        }
                    })
                }
            }
        })

        // this.info()
    },

    getCurrentPageUrl() {
        var pages = getCurrentPages() //获取加载的页面
        var currentPage = pages[pages.length - 1] //获取当前页面的对象
        var url = currentPage.route //当前页面url
        return url
    },
    getCurrentPageUrlWithArgs() {
        var pages = getCurrentPages() //获取加载的页面
        var currentPage = pages[pages.length - 1] //获取当前页面的对象
        var url = currentPage.route //当前页面url
        var options = currentPage.options || [] //如果要获取url中所带的参数可以查看options
        let userInfo = wx.getStorageSync('userInfo') || '';
        if (userInfo) {
            options.parentid = userInfo.id
        }
        //拼接url的参数
        var urlWithArgs = url + '?'
        for (var key in options) {
            var value = options[key]
            urlWithArgs += key + '=' + value + '&'
        }
        urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)

        return urlWithArgs
    },
    // 保存图片到本地
    saveImg(url) {
        // 图片文件路径，可以是临时文件路径或永久文件路径 (本地路径)，不支持网络路径
        return new Promise((resolve, reject) => {
              
             


            wx.getImageInfo({
                src: url,
                success: res => {
                   
                    wx.saveImageToPhotosAlbum({
                        filePath: res.path,
                        success: res => {
                       
                            resolve(res)
                          
                            wx.showToast({
                                title: '保存成功',
                                icon:'none'
                            })
                        },
                        complete(res) {
                            console.log('complete', res)
                           
                        },
                        fail:err=>{
                            wx.showToast({
                                title: "保存失败",
                                icon:"none"
                            })
                            reject(false)
                        }
                    })
                },
                fail: err => {
                   
                    wx.showToast({
                        title: "保存失败",
                        icon:"none"
                    })
                  
                    reject(false)
                }
            })


        })
    },
    //登录请求
    GetLogin(flag) {
        wx.login({
            success: res => {
                let code = res.code
                console.log(code)
                console.log('globalData.parentid',this.globalData.parentid)
                // Controller.testlogin({
                //         code,
                //         parentId: this.globalData.parentid,
                //     }).then(res => {
                //         console.log('getUserInfo', res)
                //         if (res.data.baseData.mobile) {
                //             wx.setStorageSync('logintoken', res.data.token)
                //         }
                //         wx.setStorageSync('logintokenlinshi', res.data.token)
                //         wx.setStorageSync('userInfo', res.data.baseData)
                //         wx.setStorageSync('sessionKey', res.data.sessionKey)
                //         if (this.tokenReadyCallback) {
                //             this.tokenReadyCallback(res);
                //         }
                //     }).catch(res => {
                //         console.log(res)
                //     })
                Controller.login({
                    code,
                    parentId:this.globalData.shareparentId||this.globalData.parentid,
                }).then(res => {
                    console.log('getUserInfo', res)
                  
                    if (res.data.baseData.mobile) {
                        wx.setStorageSync('logintoken', res.data.token)
                    }
                    wx.setStorageSync('logintokenlinshi', res.data.token)
                    wx.setStorageSync('userInfo', res.data.baseData)
                    wx.setStorageSync('sessionKey', res.data.sessionKey)
                    if (this.tokenReadyCallback) {
                        this.tokenReadyCallback(res);
                    }
                }).catch(res => {
                 
                    console.log(res)
                })
            }
        });
    },
    ToLogin(delta) {
        var that = this;
        let token = wx.getStorageSync('logintokenlinshi') || '';
        if (that.globalData.islogin) {
            that.globalData.islogin = false
           
            wx.showModal({
                title: '提示',
                content: '是否授权登录?',
                success(res) {
                    that.globalData.islogin = true
                    if (res.confirm) {
                        that.GetLogin();
                       
                        wx.getUserProfile({
                            desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                            success: (res) => {
                                if (res.userInfo) {
                                    wx.setStorageSync('wxuserInfo', res.userInfo)
                                    let wxuserInfo = res.userInfo

                                    that.updateUserInfo(res).then(res => {

                                        let userInfo = wx.getStorageSync('userInfo')

                                        userInfo.nick = wxuserInfo.nickName
                                        userInfo.portrait = wxuserInfo.avatarUrl

                                        wx.setStorageSync('userInfo', userInfo)

                                        wx.navigateTo({
                                            url: "/pages/Login/Login"
                                        })
                                    })
                                }
                            },
                            fail: (res) => {
                                wx.switchTab({
                                    url: '/pages/Index/Index'
                                })
                            }
                        })
                    } else if (res.cancel) {
                        wx.switchTab({
                            url: '/pages/Index/Index'
                        })
                        console.log('用户点击取消')
                    }
                }
            })


        }

    },
    //获取授权信息
    updateUserInfo(data) {
        return new Promise((resolve, reject) => {
            Controller.updateUserInfo({
                    sessionKey: wx.getStorageSync('sessionKey'),
                    iv: data.iv,
                    encryptedData: data.encryptedData
                })
                .then(res => {
                    console.log('获取用户信息', res)
                    if (res.code == 0) {
                        resolve(res)
                    }
                }).catch(err => {
                    reject(err)
                })
        })
    },
    //获取手机号
    updatePhoneNumber(data) {
        return new Promise((resolve, reject) => {
            Controller.updatePhoneNumber({
                    sessionKey: wx.getStorageSync('sessionKey'),
                    iv: data.iv,
                    encryptedData: data.encryptedData
                })
                .then(res => {
                    console.log('获取手机号', res)
                    if (res.code == 0) {
                        resolve(res)
                    }
                }).catch(err => {
                    reject(err)
                })
        })
    },

    globalData: {
        coupon: null,
        parentid: '',
        shareparentId:'',
        isIphoneX: false,
        statusBarHeight: 20,
        islogin: true,
        sessionKey: '',
        userInfo: '',
        wxuserInfo: '',
        logintoken: '',
        navHeight: 66,
        baseUrl: Controller.url,
        topNavigationHeight: 0,
        ques: '',
        publishGoods: {
            useStatus: '',
            leftStatus: '',
            defectStatus: '',
            info: '',
            specification: '',
            priceType: '',
            price: '',
            minPriceRate: '',
            imgUrl: '',
            frontImgUrl: '',
            sideImgUrl: '',
            bottomImgUrl: '',
            topImgUrl: '',
            otherImgUrl: '',
            goodsId: '',
            baseGoodsId: 0,
        },
        isRefresh: true
    },
    tokenReadyCallback: function () {},
})